// src/store/modules/user.js
import { login,smsLogin, getUserInfo, logout,register } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(), // 从本地存储获取 token
  userInfo: {}, // 用户基本信息
  isLoggedIn: !!getToken(), // 是否已登录
  roles: [], // 用户角色
  permissions: [] // 用户权限
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  
  SET_LOGIN_STATUS: (state, status) => {
    state.isLoggedIn = status
  },
  
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  
  RESET_STATE: (state) => {
    state.token = ''
    state.userInfo = {}
    state.isLoggedIn = false
    state.roles = []
    state.permissions = []
  }
}

const actions = {
  // 用户登录
  async login({ commit }, loginForm) {
    try {
      const response = await login(loginForm)
      
      if (response.code === 200) {
        const { token } = response.data
        commit('SET_TOKEN', token)
        commit('SET_LOGIN_STATUS', true)
        setToken(token)
        return Promise.resolve(response)
      } else {
        return Promise.reject(new Error(response.message || '登录失败'))
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },
  async smsLogin({ commit }, loginForm) {
    try {
      const response = await smsLogin(loginForm)
      
      if (response.code === 200) {
        const { token } = response.data
        commit('SET_TOKEN', token)
        commit('SET_LOGIN_STATUS', true)
        setToken(token)
        return Promise.resolve(response)
      } else {
        return Promise.reject(new Error(response.message || '登录失败'))
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },

   async register({ commit }, loginForm) {
    try {
      const response = await register(loginForm)
      
      if (response.code === 200) {
        const { token } = response.data
        commit('SET_TOKEN', token)
        commit('SET_LOGIN_STATUS', true)
        setToken(token)
        return Promise.resolve(response)
      } else {
        return Promise.reject(new Error(response.message || '登录失败'))
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },
  
  // 获取用户信息
  async getUserInfo({ commit, state }) {
    try {
      const response = await getUserInfo()
      
      if (response.code === 200) {
        commit('SET_USER_INFO', response.data)
        return Promise.resolve(response.data)
      } else {
        return Promise.reject(new Error(response.message || '获取用户信息失败'))
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },
  
  // 用户登出
  async logout({ commit, state }) {
    try {
      await logout(state.token)
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 无论请求成功与否，都要清除本地状态
      commit('RESET_STATE')
      removeToken()
    }
  },
  
  // 前端登出（不发送请求）
  fedLogout({ commit }) {
    return new Promise(resolve => {
      commit('RESET_STATE')
      removeToken()
      resolve()
    })
  }
}

const getters = {
  token: state => state.token,
  userInfo: state => state.userInfo,
  isLoggedIn: state => state.isLoggedIn,
  roles: state => state.roles,
  permissions: state => state.permissions,
  username: state => state.userInfo.username,
  avatar: state => state.userInfo.avatar,
  nickname: state => state.userInfo.nickName
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}